package com.appspot.bibtable.model;

import java.util.Date;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.appspot.bibtable.PMF;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;

@PersistenceCapable
public class UserInfo
{
	@PrimaryKey
	@Persistent
	private Key key;

	@Persistent
	private SortedSet<Key> bookmarks;

	@Persistent
	private Date registeredDate;

	@Persistent
	private Integer displayCount;

	public UserInfo()
	{
		bookmarks = new TreeSet<Key>();
		displayCount = 50;
	}

	public static UserInfo getUserInfoOf(User user)
	{
		PersistenceManager manager = PMF.get().getPersistenceManager();
		UserInfo userInfo = null;
		try
		{
			userInfo = getUserInfoOf(user, manager);
		}
		finally
		{
			manager.close();
		}
		return userInfo;
	}

	public static UserInfo getUserInfoOf(User user, PersistenceManager manager)
	{
		if (user == null)
		{
			return null;
		}

		UserInfo userInfo = null;
		try
		{
			userInfo = manager.getObjectById(UserInfo.class, user.getUserId());
		}
		catch (JDOObjectNotFoundException ex)
		{
			// Fine.
		}
		return userInfo;
	}

	public Key getKey()
	{
		return key;
	}

	public void setKey(User user)
	{
		this.key = KeyFactory.createKey(UserInfo.class.getSimpleName(), user.getUserId());
	}

	public Set<Key> getBookmarks()
	{
		return bookmarks;
	}

	public void bookmark(Key key)
	{
		getBookmarks().add(key);
	}

	public void bookmark(Reference reference)
	{
		bookmark(reference.getKey());
	}

	public void unbookmark(Key key)
	{
		getBookmarks().remove(key);
	}

	public void unbookmark(Reference reference)
	{
		unbookmark(reference.getKey());
	}

	public boolean isBookmarking(Key key)
	{
		return getBookmarks().contains(key);
	}

	public boolean isBookmarking(Reference reference)
	{
		return reference != null && isBookmarking(reference.getKey());
	}

	public int countBookmark()
	{
		return getBookmarks().size();
	}

	public Date getRegisteredDate()
	{
		return registeredDate;
	}

	public void setRegisteredDate(Date registeredDate)
	{
		this.registeredDate = registeredDate;
	}

	public int getDisplayCount()
	{
		return displayCount == null ? 50 : displayCount.intValue();
	}

	public void setDisplayCount(int displayCount)
	{
		this.displayCount = displayCount;
	}
}
